import requests
from loguru import logger

from config import ENV


def request_hook(response,*args,**kwargs):
    logger.debug(f"接口响应数据为：{response.text}")


def login():
    data = {
        "url": ENV.HOST + "adminapi/login",
        "method":"GET",
        "params": {
            "username": ENV.USERNAME,
            "password": ENV.PASSWORD
        }
    }
    return requests.request(**data).json()["data"]["token"]

class BaseRequest:
    def __init__(self):
        self._token = login()
        self._session = requests.Session()
        self._session.headers = {
            "content-type": "application/json",
            "token": self._token
        }
        self._session.hooks["response"].append(request_hook)
        self._request = self._session

    def post(self,api_name,url,data):
        logger.debug(f"接口-{api_name}-请求数据为: {ENV.HOST + url} {data}")
        response = self._request.post(ENV.HOST + url,json = data)
        return response.json()

    def get(self,api_name,url,params):
        logger.debug(f"接口-{api_name}-请求数据为：{ENV.HOST + url} {params}")
        response = self._request.get(ENV.HOST + url, params=params)
        return response.json()

    def put(self,api_name,url,data):
        logger.debug(f"接口-{api_name}-请求数据为: {ENV.HOST + url} {data}")
        response = self._request.post(ENV.HOST + url, json=data)
        return response.json()

    def delete(self,api_name,url):
        logger.debug(f"接口-{api_name}-请求数据为: {ENV.HOST + url}")
        response = self._request.delete(ENV.HOST + url)
        return response.json()
